import React,{useEffect,useState} from 'react'

const VoiceAssistant:React.FC=()=>{
    const [img,setImg]=useState(true);
    const [flag,setFlag]=useState(false);
    const[isRecording,setIsRecording]=useState(false);
    const [transcript,setTranscript]=useState('');
    useEffect(()=>{
        // 创建语音识别实例
        const recognition=new (window.webkitSpeechRecognition || window.SpeechRecognition)();
        recognition.lang='zh-CN';//设置语言为中文
        //当语音识别开始时触发
        recognition.onstart=()=>{
            setIsRecording(true);
            console.log('语音识别开始');
        };
        //当语音识别结束时触发
        recognition.onresult=(event:any)=>{
            const transcript=event.results[0][0].transcript;
            setTranscript(transcript);//将识别结果保存到状态中
            console.log('识别结果：',transcript);
        };
        //语音识别出错时触发
        recognition.onerror=(error:any)=>{
           console.log('语音识别出错',error.error);
           if(error.error=='not-allowed'){
            console.log('请允许浏览器使用麦克风');
           }
           else if(error.error=='audio-capture'){
            console.log('无法获取音频输入');
           }
           else if(error.error=='network'){
               console.log('网络错误');
           }
           else if(error.error=='no-speech'){
               console.log('没有检测到语音');
           }
            else if(error.error=='service-not-allowed'){
               console.log('服务不允许');
           }
            else if(error.error=='bad-grammar'){
               console.log('语法错误');
           }
            else if(error.error=='language-not-supported'){
               console.log('不支持的语言');
           }
        };
        //语音识别结束时触发
        recognition.onend=()=>{
            setIsRecording(false);
            console.log('语音识别结束')
        };
        if(isRecording){
            recognition.start();
        }
        return ()=>{
            recognition.stop();
        };
    },[isRecording]);
    const startRecording=()=>{
        setIsRecording(true);
    };
    const stopRecording=()=>{
        setIsRecording(false);
    };
    const RevImg=()=>{
        setImg(!img);
        setFlag(true);
        if(isRecording){
            stopRecording();
        }
        else{
            startRecording();
        }
    };
       const ConsImg=()=>{
        setImg(!img);
        setFlag(false);
       };
       return (
        <div>
            <button onClick={RevImg}>5555</button>
            <button onClick={ConsImg}>6666</button>
            <p>{transcript}</p>
        </div>
       )
}
export default VoiceAssistant;
